use crate::{Solution, SolutionPair};
use std::fs::read_to_string;

fn parse_range(range_str: &str) -> (u32, u32) {
    let range = range_str.split('-').collect::<Vec<&str>>();
    let range_start = range[0].parse::<u32>().unwrap();
    let range_end = range[1].parse::<u32>().unwrap();

    (range_start, range_end)
}

fn solve_part1(input: &str) -> u32 {
    input
        .lines()
        .filter(|line| {
            let ranges = line.split(',').collect::<Vec<&str>>();

            let range1 = parse_range(ranges[0]);
            let range2 = parse_range(ranges[1]);

            (range1.0 <= range2.0 && range1.1 >= range2.1)
                || (range1.0 >= range2.0 && range1.1 <= range2.1)
        })
        .count() as u32
}

fn solve_part2(input: &str) -> u32 {
    input
        .lines()
        .filter(|line| {
            let ranges = line.split(',').collect::<Vec<&str>>();

            let range1 = parse_range(ranges[0]);
            let range2 = parse_range(ranges[1]);

            (range1.0 <= range2.1) && (range2.0 <= range1.1)
        })
        .count() as u32
}

pub fn solve() -> SolutionPair {
    let input = read_to_string("input/day04.txt").unwrap();

    let sol1: u32 = solve_part1(&input);
    let sol2: u32 = solve_part2(&input);

    (Solution::from(sol1), Solution::from(sol2))
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::etc::utils;

    #[test]
    fn part1() {
        let input = utils::to_multiline_string(vec![
            "2-4,6-8", "2-3,4-5", "5-7,7-9", "2-8,3-7", "6-6,4-6", "2-6,4-8",
        ]);
        assert_eq!(2, solve_part1(&input));
    }

    #[test]
    fn part1_2() {
        let input = utils::to_multiline_string(vec![
            "6-8,2-4", "4-5,2-3", "7-9,5-7", "3-7,2-8", "4-6,6-6", "4-8,2-6",
        ]);
        assert_eq!(2, solve_part1(&input));
    }

    #[test]
    fn part2() {
        let input = utils::to_multiline_string(vec![
            "2-4,6-8", "2-3,4-5", "5-7,7-9", "2-8,3-7", "6-6,4-6", "2-6,4-8",
        ]);
        assert_eq!(4, solve_part2(&input));
    }
}
